import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

/// 一个委托，由[Router]小部件用来将路由信息解析为[routessettings]类型的配置。
class RikiRouteInformationParser extends RouteInformationParser<RouteSettings> {
  /// 将给定的路由信息转换为经过解析的数据以传递给
  /// [RikiRouterDelegate].
  @override
  Future<RouteSettings> parseRouteInformation(
      RouteInformation routeInformation) {
    String name = routeInformation.location!;
    final Uri? uri = Uri.tryParse(name);
    if (uri != null && uri.queryParameters.isNotEmpty) {
      name = name.substring(0, name.indexOf('?'));
    }

    return SynchronousFuture<RouteSettings>(RouteSettings(
      name: name,
      arguments: uri?.queryParameters,
    ));
  }

  /// 从给定的配置恢复路由信息。
  /// [RikiRouterDelegate.currentConfiguration]
  @override
  RouteInformation restoreRouteInformation(RouteSettings configuration) {
    String location = configuration.name!;
    if (configuration.arguments != null &&
        configuration.arguments is Map<String, dynamic>) {
      final Map<String, dynamic> arguments =
          configuration.arguments as Map<String, dynamic>;
      final List<String> keys = arguments.keys.toList();
      for (int i = 0; i < keys.length; i++) {
        final String key = keys[i];
        if (i == 0) {
          location += '?';
        } else {
          location += '&';
        }
        location += '$key=${arguments[key]}';
      }
    }
    return RouteInformation(
      location: location,
    );
  }
}
